import React, { useState, useEffect } from 'react';
import { Card } from '../../components/Card';
import { Button } from '../../components/Button';
import { Modal } from '../../components/Modal';
import { useChromeStorage } from '../../hooks/useChromeStorage';
import './ContentTab.css';

// Import longevity content - in a real app, this would be loaded from a data file
const LONGEVITY_CONTENT = window.LONGEVITY_CONTENT || [];

export const ContentTab = () => {
  const [userContent, setUserContent] = useState([]);
  const [favorites, setFavorites] = useState([]);
  const [showAddModal, setShowAddModal] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    chrome.storage.local.get(['userContent', 'favorites'], (result) => {
      setUserContent(result.userContent || []);
      setFavorites(result.favorites || []);
      setLoading(false);
    });
  };

  const allContent = [...LONGEVITY_CONTENT, ...userContent];

  const handleFavorite = async (id) => {
    const newFavorites = favorites.includes(id)
      ? favorites.filter(f => f !== id)
      : [...favorites, id];
    
    await chrome.storage.local.set({ favorites: newFavorites });
    setFavorites(newFavorites);
  };

  const handleAddContent = async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const newContent = {
      id: `user-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      title: formData.get('title'),
      link: formData.get('link') || '',
      description: formData.get('description') || '',
      category: formData.get('category') || 'Custom',
      timestamp: Date.now()
    };

    const updatedContent = [...userContent, newContent];
    await chrome.storage.local.set({ userContent: updatedContent });
    setUserContent(updatedContent);
    setShowAddModal(false);
    e.target.reset();
  };

  const handleCardClick = (link) => {
    if (link) {
      chrome.tabs.create({ url: link });
    }
  };

  if (loading) {
    return <div className="loading">Loading content...</div>;
  }

  return (
    <div className="content-tab">
      <div className="section-header">
        <h2>Longevity Information</h2>
        <Button onClick={() => setShowAddModal(true)}>+ Add</Button>
      </div>

      {allContent.length === 0 ? (
        <div className="empty-state">
          <p>No content available. Add some longevity information!</p>
        </div>
      ) : (
        <div className="content-list">
          {allContent.map((item) => {
            const isFavorite = favorites.includes(item.id);
            const link = item.link || (item.references && item.references[0]?.url) || '#';
            
            return (
              <Card
                key={item.id}
                className="content-card"
                onClick={() => handleCardClick(link)}
              >
                <h3>
                  {item.title}
                  <button
                    className={`favorite-btn ${isFavorite ? 'active' : ''}`}
                    onClick={(e) => {
                      e.stopPropagation();
                      handleFavorite(item.id);
                    }}
                  >
                    {isFavorite ? '⭐' : '☆'}
                  </button>
                </h3>
                <span className="category">{item.category || 'General'}</span>
                <p>{item.description || ''}</p>
                {item.references && (
                  <div className="references">
                    <strong>References:</strong>
                    {item.references.map((ref, idx) => (
                      <a
                        key={idx}
                        href={ref.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        onClick={(e) => e.stopPropagation()}
                      >
                        {ref.text}
                      </a>
                    ))}
                  </div>
                )}
              </Card>
            );
          })}
        </div>
      )}

      <Modal isOpen={showAddModal} onClose={() => setShowAddModal(false)} title="Add Longevity Content">
        <form onSubmit={handleAddContent}>
          <div className="form-group">
            <input type="text" name="title" placeholder="Title" required />
          </div>
          <div className="form-group">
            <input type="url" name="link" placeholder="Link (optional)" />
          </div>
          <div className="form-group">
            <textarea name="description" placeholder="Description" rows="3"></textarea>
          </div>
          <div className="form-group">
            <input type="text" name="category" placeholder="Category" defaultValue="Custom" />
          </div>
          <Button type="submit">Add Content</Button>
        </form>
      </Modal>
    </div>
  );
};
